/*
 * Copyright 2012 Gregor Schauer
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package at.schauer.gregor.vienna.convert.vienna.misc;

import at.schauer.gregor.vienna.adapter.io.SerializableFileInput;
import at.schauer.gregor.vienna.convert.vienna.base.SeparatorConverter;
import at.schauer.gregor.vienna.convert.vienna.base.StringConstructorConverter;
import at.schauer.gregor.vienna.exception.SerializerException;

import java.io.IOException;

/**
 * @author Gregor Schauer
 */
public class SerializableFileInputConverter extends StringConstructorConverter<SerializableFileInput> implements SeparatorConverter<SerializableFileInput> {
	@Override
	public SerializableFileInput sourceToTarget(String source, Class<? extends SerializableFileInput> targetClass) {
		int index = source.lastIndexOf(getSeparator());
		String file = source.substring(0, index);
		long pos = Long.parseLong(source.substring(index + 1));
		try {
			SerializableFileInput in = super.sourceToTarget(file, targetClass);
			if (pos > 0) {
				in.skip(pos);
			}
			return in;
		} catch (IOException e) {
			throw new SerializerException(e);
		}
	}

	@Override
	public String targetToSource(SerializableFileInput target) {
		String path;
		try {
			path = target.getFile().getCanonicalPath();
		} catch (IOException ignored) {
			path = target.getFile().getAbsolutePath();
		}

		try {
			target.getFD().sync();
			return path + getSeparator() + target.getBytesRead();
		} catch (IOException e) {
			throw new SerializerException(e);
		}
	}

	@Override
	public String getSeparator() {
		return "#";
	}
}
